<template>
  <div class="wrapper">
    <!--<vuedraggable
      class="vue-draggable"
      tag="ul"
      v-model="attrList"
      draggable=".draggable-item"
      @start="onDragStart"
      @end="onDragEnd"
    >-->
      <!-- 拖拽元素 -->
      <li
        v-for="(kind, kindIndex) in attrList"
        :key="kind.key"
        class="draggable-item"
      >
        <div class="kind">
          <div class="kind-item">
            <div class="kind-name">规格名：</div>
            <el-input size="small" class="kind-input" v-model="kind.name"></el-input>
          </div>
          <div class="attr">
            <div class="attr-item">
              <div class="attr-name">规格值：</div>
              <div class="attr-input-wrapper" v-for="(attr,attrIndex) in kind.attrs" :key="attr.key">
                <el-input size="small" class="attr-input" v-model="attr.name" @change="(val)=>changeAttrName(kindIndex,attrIndex,val)"></el-input>
                <i class="el-icon-error attr-input-delete"  @click="delAttr(kindIndex,attrIndex)" />
              </div>
              <el-button type="text" @click="addAttr(kindIndex)">添加规格值</el-button>
            </div>
          </div>
        </div>
        <i class="el-icon-error kind-del-btn" @click="tapDelKind(kindIndex)" />
      </li>
      
    <!--</vuedraggable>-->
    <div class="attr-tool">
      <el-button type="text" @click="tapAddKind">添加规格</el-button>
      <!--<el-button type="text">批量设置</el-button>-->
      <!--<el-button type="text" v-if="attrList.length > 0">自定义排序</el-button>-->
      <span style="color:red;font-size:13px;">【当前若变更属性规格、属性值、名称等一切操作，下方表格都会清空，请先确认属性，再输入值】</span>
    </div>
    <div class="attr-content">
      <el-table :data="attrDataTable" :span-method="objectSpanMethod" border fit highlight-current-row max-height="500" style="width: 100%;">
          <el-table-column
            v-for="(kind) in attrList" :key="kind.id"
            :prop="kind.name"
            :label="kind.name"
            width="100">
          </el-table-column>
          <el-table-column
            type="index"
            width="50"
            label="序号">
          </el-table-column>
          <el-table-column v-for="(item) in options" :key="item.field" :width="item.type =='cover' ? '80' : (item.width ? item.width : '150')" :min-width="item.minWidth" align="center" :label="item.label">
            <template slot-scope="{row}">
              <template v-if="item.type =='text'">
                <el-input v-model="row[item.field]" class="edit-input" :size="item.size ? item.size:'mini'"/>
              </template>
              <template v-if="item.type =='number'">
                <el-input-number v-model="row[item.field]" :size="item.size ? item.size:'mini'" :precision="item.precision ? item.precision : 0" :step="item.step ? item.step : 1" :min="item.min ? item.min : 0"  :max="item.max ? item.max : 999999999" class="edit-input input-number"></el-input-number>
              </template>
              <template v-if="item.type =='price'">
                <el-input-number  :controls="false"  v-model="row[item.field]" :size="item.size ? item.size:'mini'" :precision="item.precision ? item.precision : 2" :step="item.step ? item.step : 1" :min="item.min ? item.min : 0" :max="item.max ? item.max : 999999999" class="edit-input input-number"></el-input-number>
              </template>
              <template v-if="item.type =='select'">
                <el-select v-model="row[item.field]" :size="item.size ? item.size:'mini'"  clearable>
                  <el-option
                    v-for="options in item.options"
                    :key="options.value"
                    :label="options.label"
                    :value="options.value">
                  </el-option>
                </el-select>
              </template>
              <!--读取数据下拉选择框-->
              <template v-if="item.type=='selectdata'">
                <el-select v-model="row[item.field]" :size="item.size ? item.size:'mini'"  :placeholder="item.placeholder" :filterable="item.filterable ? true : false" :disabled="item.readonly ? true : false"  clearable>
                  <template v-for="group in item.options">
                    <el-option-group
                      v-if="item.children && item.children.length > 0"
                      :key="group.value"
                      :label="group.label">
                        <el-option
                          v-for="item in group.children"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-option-group>
                      <el-option
                        v-else
                        :key="group.value"
                        :label="group.label"
                        :value="group.value">
                      </el-option>
                    </template>
                </el-select>
              </template>
              <!--单张封面图片选择-->
              <template v-if="item.type == 'cover'">
                <el-upload
                  class="cover-uploader"
                  name="uploadFileData"
                  :data="uploadPlatformData"
                  :action="$config.uploadImgUrl"
                  :headers="$store.getters.userInfo.user_token ? {'User-Token' : $store.getters.userInfo.user_token} : {}"
                  :show-file-list="false"
                  :on-success="(e)=>uploadCoverSuccess(e,row,item.field)">
                    <img v-if="row[item.field]" :src="row[item.field]" class="cover">
                    <i v-else class="el-icon-plus cover-uploader-icon"></i>
                </el-upload>
              </template>
              <template v-if="item.type =='selectcreate'">
                <el-select v-model="row[item.field]" multiple
                filterable
                allow-create
                default-first-option
                clearable
                :placeholder="item.placeholder ? item.placeholder : ''">
                  <el-option
                    v-for="options in item.options"
                    :key="options.value"
                    :label="options.label"
                    :value="options.value">
                  </el-option>
                </el-select>
              </template>
            </template>
            

          </el-table-column>
        </el-table>
    </div>
  </div>
</template>

<script>
import vuedraggable from 'vuedraggable'
import {isArray} from '@/utils';
export default {
  name: 'dialogAttrEditor',
  props: {
    // 最终数据通过value传递
    value: {
      type: Array,
      default () {
        return []
      }
    },
    field:{
      type:String
    },
    options:{
      type:Array,
      default(){
        return []
      }
    }
  },

  data () {
    return {
      uploadPlatformData:{
        platform_app_id:this.$store.getters.appInfo.platform_app_id,
        platform_user_id:this.$store.getters.appInfo.platform_user_id,
        platform_app_user_id:this.$store.getters.appInfo.platform_app_user_id
      },
      attrData: [],
      attrDataTable:[]
    }
  },

  computed: {
    attrList: {
      get () {
        return this.value
      },
      set (val) {
        // 同步v-model
        this.$emit('update:value', val);
      }
    }
  },
  mounted () {

  },
  created(){
  },
  methods: {
    init(){
        this.attrDataTable = [];
        this.attrData = [];
    },
    updateTableForm(){
      let attrData = [];
      let kindAttrArr = [];
      //循环规格种类，乘以当前规格下的属性数量，得到最终行数
      this.attrList.forEach(kind => {
        let attrArr = [];
        kind.attrs.forEach(attr=>{
          attrArr.push(attr.name);
        })
        kindAttrArr.push(attrArr);
      })
      if (kindAttrArr.length == 0) {
        this.attrDataTable = []
        return [];
      }
      let rows = this.makeTable(kindAttrArr);
      let data = {};
      //插入数据
      if (rows.length == 0) {
        this.attrDataTable = []
        return [];
      }
      rows.forEach(group =>{
        data = {};
        if (isArray(group)) {
          group.forEach((colName,colIndex)=>{
            data[this.attrList[colIndex].name] = colName;
          })
        } else {
          data[this.attrList[0].name] = group;
        }
        attrData.push(data)
      })
      this.attrDataTable =  attrData;
      this.$emit('updateAttrData',this.field,attrData)
    },
    changeAttrName(kindIndex,attrIndex,attrName){
      //this.updateTableForm();
      //return;
      //待完善，修改属性时不重置表格；
      //同待完善，属性名称不能是id，不然键名和主键重复出现问题
      if (attrName.toUpperCase() == 'ID') {
        this.attrList[kindIndex].attrs[attrIndex].name = '';
        this.$tool.toast('属性名称不能使用关键词id');
        return false;
      }
      if (attrName != '') {
        let count = 0;
        this.attrList[kindIndex].attrs.forEach(item=>{
          if (item.name == attrName) count++;
        })
        if (count > 1) {
          this.attrList[kindIndex].attrs[attrIndex].name = '';
          return this.$tool.toast(attrName + '属性值已存在，不可重复添加');
        }
      }
      let rowIndexArr;
      let rowNum = 1;
      let colNum = 1;
      for (let i = kindIndex+1; i < this.attrList.length;i++) {
        rowNum *= this.attrList[i].attrs.length;
      }
      for (let i = kindIndex; i > 0; i--){
        colNum *= this.attrList[i].attrs.length;
      }
      //rowNum代表连续替换多少行，colNum代表每隔多少行替换一次
      //j就代表了连续替换的行数
      //i就代表了要替换多少次
      console.log('kindIndex:'+kindIndex+',attrIndex:'+attrIndex + ',rowNum:'+rowNum+',colNum:'+colNum);
      for (let i = 0; i < colNum;i++){
        console.log('i:'+i);
        for (let j = 0; j < rowNum; j++){
          console.log('j:'+j);
          
          //this.attrDataTable[attrIndex*rowNum + i*colNum + j][this.attrList[kindIndex].name] = attrName;
          let tableIndex = attrIndex*rowNum;
          tableIndex += i*colNum;
          tableIndex += j;
          console.log('行index：'+tableIndex);
          this.attrDataTable[tableIndex][this.attrList[kindIndex].name] = attrName;
        }
      }
      
    },
    uploadCoverSuccess(e,row,field){
      row[field] = e.data.url;
    },
    getAttrData(){
      return this.attrDataTable;
    },
    setAttrData(attrData = []){
      this.attrDataTable = attrData;
    },
    getAttrList(){
      return this.attrList;
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      return;
      let attrNum = this.attrList.length;
      let rowspan = 1;
      let colspan = 1;
      if (this.attrList.length < 2 || columnIndex > attrNum - 1) return {rowspan,colspan};

      for (let i = columnIndex+1; i < attrNum; i++){
        rowspan *= this.attrList[i].attrs.length;
      }
      if (rowIndex % rowspan === 0) {
        return {rowspan,colspan};
      } else {
        return {rowspan:0,colspan:0};
      }
    },
    tapAddKind(){
      if (this.attrDataTable.length > 0){
        this.$tool.confirm('新增后，将会清空下方明细数据，是否继续？').then(()=>{
          this.addKind();
        }).catch(()=>{});
      } else {
        this.addKind();
      }
      
    },
    addKind(){
      let attr = {
        key:new Date().getTime(),
        name:'',
        attrs:[]
      };
      this.attrList.push(attr);
      this.updateTableForm();
    },
    tapDelKind(index){
      if (this.attrDataTable.length > 0) {
        this.$tool.confirm('删除后，将会重置下方明细数据，是否继续？').then(()=>{
          this.delKind(index);
        }).catch(()=>{});
      } else {
        this.delKind(index);
      }
      
    },
    delKind(index){
      this.attrList.splice(index,1);
      this.updateTableForm();
    },
    addAttr(kindIndex){
      this.attrList[kindIndex].attrs.push({key:new Date().getTime(),name:''});
      this.updateTableForm();
    },
    delAttr(kindIndex,attrIndex){
      this.attrList[kindIndex].attrs.splice(attrIndex,1);
      this.updateTableForm();
    },
    submit(){
      
    },
    onDragStart (e) {
      e.target.classList.add('hideShadow')
    },
    onDragEnd (e) {
      e.target.classList.remove('hideShadow')
    },
    makeTable(kindAttrArr){
      if(kindAttrArr.length === 1){
          return kindAttrArr.shift(); //树最底层的叶节点直接返回
      }
      let start_tree = kindAttrArr.shift(); //递归取出每一层的所有可能与下层拼接
      let tree= this.makeTable(kindAttrArr);
      let skuArr = []
      start_tree.forEach((item, index) => {
          tree.forEach((item_t, index_t) => {
            item_t = isArray(item_t) ? item_t : [item_t]
            skuArr.push([...[item], ...item_t]);
          })
      })
      return skuArr;
    },
    makeTableArr(arr){
      //纯数组如[['A1','A2'],['B1',B2]]可以
        if(arr.length === 1){
            return arr.shift(); //树最底层的叶节点直接返回
        }
        let start_tree = arr.shift(); //递归取出每一层的所有可能与下层拼接
        let tree= this.makeTableArr(arr);
        let skuArr = []
        start_tree.forEach((item, index) => {
            tree.forEach((item_t, index_t) => {
                item_t = isArray(item_t) ? item_t : [item_t]
                skuArr.push([...[item], ...item_t]);
            })
        })
        return skuArr;
    }
  },
  components: { vuedraggable }
}
</script>

<style lang="less" scoped>
  .wrapper{margin:20px auto;}
  .kind-item{display: flex;align-items: center;margin-bottom:10px;}
  .kind-input{width:150px;}
  .attr-item{display: flex;align-items: center;flex-wrap: wrap;}
  .attr-input-wrapper{position: relative;}
  .attr-input-delete{position: absolute;right:6px;top:-6px;z-index:2;cursor: pointer;}
  .attr-input-delete:hover{color:#409EFF;}
  .attr-input{width:100px;margin-right:10px;}
  .attr-tool{background: #F8F8F8;}
  .kind-del-btn{position: absolute;right:10px;top:10px;z-index:2;cursor: pointer;}
  .kind-del-btn:hover{color:#409EFF;}
  .input-number{width:120px;}
  .cover-uploader{width:65px;height:65px;}
  .cover-uploader .cover-uploader-icon{width:60px;height:60px;line-height: 60px;}
  .cover{width:60px;height:60px;}

  // 拖拽
  .vue-draggable {display: flex;flex-wrap: wrap;padding-left:0;}
  .draggable-item {
    list-style-type: none;
    margin-right: 5px;
    margin-bottom: 5px;
    background:#F4F4F4;
    width:100%;
    padding:15px;
    margin-bottom:10px;
    border-radius: 6px;
    position: relative;
    overflow: hidden;
    .shadow {
      position: absolute;
      top: 0;
      right: 0;
      background-color: rgba(0,0,0,.5);
      opacity: 0;
      transition: opacity .3s;
      color: #fff;
      font-size: 20px;
      line-height: 20px;
      padding: 2px;
      cursor: pointer;
    }
    &:hover {
      .shadow {
        opacity: 1;
      }
    }
  }
  &.hideShadow {
    .shadow {
      display: none;
    }
  }
</style>
